package com.weichuanbo.xwdz.im;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.weichuanbo.xwdz.app.Common;
import com.weichuanbo.xwdz.app.utils.LogUtil;
import com.weichuanbo.xwdz.app.utils.SaveBeanUtil;
import com.weichuanbo.xwdz.mvp.model.entity.UserBean;

import java.util.List;

import io.rong.common.RLog;
import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import timber.log.Timber;

/**
 * @author : ssy
 * @date : 2018/9/5 14:23
 * @E-Mail ：1161209667@qq.com
 * 融云相关监听 事件集合类
 */
public class SealAppContext implements RongIMClient.OnReceiveMessageListener {


    private static final String TAG = "sealAppContext";
    private static SealAppContext mRongCloudInstance;
    private final Context mContext;

    public SealAppContext(Context mContext) {
        this.mContext = mContext;
        initListener();
        SealUserInfoManager.init(mContext);
    }

    /**
     * 初始化 RongCloud.
     *
     * @param context 上下文。
     */
    public static void init(Context context) {
        if (mRongCloudInstance == null) {
            synchronized (SealAppContext.class) {
                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new SealAppContext(context);
                }
            }
        }

    }

    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static SealAppContext getInstance() {
        return mRongCloudInstance;
    }

    public Context getContext() {
        return mContext;
    }

    /**
     * init 后就能设置的监听
     */
    private void initListener() {
        RongIM.setOnReceiveMessageListener(this);
//        RongIM.setConversationBehaviorListener(this);//设置会话界面操作的监听器。
//        RongIM.setConversationListBehaviorListener(this);
//        RongIM.setConnectionStatusListener(this);
////        RongCallClient.setReceivedCallListener(this);
//        RongIM.setUserInfoProvider(this, true);
//        RongIM.setGroupInfoProvider(this, true);
//        RongIM.setLocationProvider(this);//设置地理位置提供者,不用位置的同学可以注掉此行
//        setInputProvider();
//        //setUserInfoEngineListener();//移到SealUserInfoManager
//        setReadReceiptConversationType();
//        RongIM.getInstance().enableNewComingMessageIcon(true);
//        RongIM.getInstance().enableUnreadMessageIcon(true);
//        RongIM.getInstance().setGroupMembersProvider(this);
//        //RongIM.setGroupUserInfoProvider(this, true);//seal app暂时未使用这种方式,目前使用UserInfoProvider
//        RongIM.getInstance().setSendMessageListener(this);
//        BroadcastManager.getInstance(mContext).addAction(Const.DROP_LINE, new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                //im掉线，重新登陆
//                loginIm();
//            }
//        });
//        BroadcastManager.getInstance(mContext).addAction(Const.EXIT, new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                quit(false);
//            }
//        });
    }


    private void setReadReceiptConversationType() {
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.DISCUSSION
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
    }

    private void setInputProvider() {

        List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules();
        IExtensionModule defaultModule = null;
        if (moduleList != null) {
            for (IExtensionModule module : moduleList) {
                if (module instanceof DefaultExtensionModule) {
                    defaultModule = module;
                    break;
                }
            }
            if (defaultModule != null) {
                RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule);
//                RongExtensionManager.getInstance().registerExtensionModule(new SealExtensionModule());
            }
        }
    }


    @Override
    public boolean onReceived(Message message, int i) {
        return false;
    }


    public RongIMClient.ConnectCallback getConnectCallback() {
        RongIMClient.ConnectCallback connectCallback = new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
               RLog.e(TAG ,"ConnectCallback connect onTokenIncorrect");
                // TODO: 2018/4/18 下面这段要打开，改成请求自己服务器
//                SealUserInfoManager.getInstance().reGetToken();
            }

            @Override
            public void onSuccess(String s) {
//                Timber.tag(TAG).w("ConnectCallback connect onSuccess");
                SharedPreferences sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
                sp.edit().putString(Common.Const.SEALTALK_LOGIN_ID, s).commit();
                //设置当前用户的头像和昵称
//                SealUserInfoManager.getInstance().openDB();
                Object bean = SaveBeanUtil.getBean(mContext, Common.Const.VIPINFO);
                if (bean != null) {
                    UserBean loginSucessBean = (UserBean) bean;
                    RongIM.getInstance().setCurrentUserInfo(new UserInfo(s,
                            loginSucessBean.getNickname(),
                            Uri.parse(loginSucessBean.getHead_img().toString())));
                }
            }

            @Override
            public void onError(final RongIMClient.ErrorCode e) {
                LogUtil.d(TAG, "ConnectCallback connect onError-ErrorCode=" + e);
            }
        };
        return connectCallback;
    }

    /**
     * 登陆Im
     * @param rongcloud_token
     */
    public void loginIm(String rongcloud_token) {
        if (!TextUtils.isEmpty(rongcloud_token)) {
            RongIM.connect(rongcloud_token, getConnectCallback());
        }
    }

}
